package com.flowerplus.store.common.data.http;


import com.flowerplus.store.Logger;
import com.flowerplus.store.common.execption.ApiException;
import com.flowerplus.store.common.execption.utils.ExceptionHandle;
import com.flowerplus.store.common.structure.mvp.AbsView;
import com.flowerplus.store.common.structure.mvp.BaseView;

import rx.Subscriber;

/**
 * Created by hcqi on.
 * Des:
 * Date: 2017/4/11
 */

public abstract class AppSubscriber<T> extends Subscriber<T> {

    BaseView mView;
    boolean mProgress;

    public AppSubscriber(BaseView view) {
        this(view, true);
    }

    public AppSubscriber(BaseView view, boolean progress) {
        this.mView = view;
        mProgress = progress;
    }

    @Override
    public void onStart() {
        super.onStart();
        if (mProgress) if (mView != null) mView.showLoading();
    }

    @Override
    public void onCompleted() {
        if (mProgress) if (mView != null) mView.hideLoading();
    }

    @Override
    public void onError(Throwable e) {
        if (mProgress) if (mView != null) mView.hideLoading();
        e.printStackTrace();
        if (e instanceof ApiException) {
            error(((ApiException) e).getCode(), e.getMessage());
        } else {
            String msg = ExceptionHandle.handle(e);
            Logger.d(msg);
            error(-1, msg);
        }
    }


    @Override
    public void onNext(T t) {
        next(t);
    }

    public abstract void next(T t);

    public void error(int code, String e) {
        if (mView != null) {
            if (mView instanceof AbsView) {
                ((AbsView) mView).error(code, e);
            } else {
                mView.error(e);
            }
        }
    }

}
